package com.salton123.rpvoicer;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.salton123.voice.player.AudioPlayerHelper;
import com.salton123.voice.player.SimpleOnPlayerStateChangeListener;
import com.salton123.voice.recorder.AudioRecorderHelper;
import com.salton123.voice.recorder.SimpleOnRecordStateChangeListener;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class RPVoicerUIActivity extends Activity {
    private TextView tvRevert, tvRecord, tvPlay;
    private int REQUEST_CODE = 0x101;
    private String[] permissions = getPermissionArr();
    private AudioRecorderHelper mAudioRecorderHelper;
    private AudioPlayerHelper mAudioPlayerHelper;
    private TextView tvTime, tvTotalTime, tvSave;
    private boolean isClickToPlay = false;
    private String mCurrentPlayingUrl = "http://static.qxinli.com/srv/voice/201702281645261757.mp3";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAudioRecorderHelper = AudioRecorderHelper.getInstance();
        mAudioPlayerHelper = AudioPlayerHelper.getInstance();
        mAudioPlayerHelper.init(getApplication());
        if (!isPermissionGrant(this)) {
            if (Build.VERSION.SDK_INT >= 23) {
                requestPermissions(permissions, REQUEST_CODE);
            }
        }
        setContentView(R.layout.activity_rpvoicer_ui);
        tvRevert = findViewById(R.id.tvRevert);
        tvRecord = findViewById(R.id.tvRecord);
        tvPlay = findViewById(R.id.tvPlay);
        tvTime = findViewById(R.id.tvTime);
        tvTotalTime = findViewById(R.id.tvTotalTime);
        tvSave = findViewById(R.id.tvSave);
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAudioRecorderHelper.release();
            }
        });
        tvRevert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "重录", Toast.LENGTH_LONG).show();
                mAudioPlayerHelper.pause();
            }
        });
        tvRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAudioRecorderHelper.isRecording()) {
                    mAudioRecorderHelper.stop();
                    Toast.makeText(getApplicationContext(), "停止录制", Toast.LENGTH_LONG).show();
                    tvRecord.setText("开始录制");
                    mCurrentPlayingUrl = mAudioRecorderHelper.getUniteAudioFile().getAbsolutePath();
                } else {
                    if (mAudioPlayerHelper.isPlaying()) {
                        mAudioPlayerHelper.stop();
                        isClickToPlay = false;
                    }
                    Toast.makeText(getApplicationContext(), "开始录制", Toast.LENGTH_LONG).show();
                    tvRecord.setText("停止录制");
                    mAudioRecorderHelper.path("/sdcard/voice/");
                    mAudioRecorderHelper.start();
                }
            }
        });
        tvPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAudioPlayerHelper.isPlaying()) {
                    tvPlay.setText("继续");
                    Toast.makeText(getApplicationContext(), "继续", Toast.LENGTH_LONG).show();
                    mAudioPlayerHelper.pause();
                } else {
                    if (isClickToPlay) {
                        tvPlay.setText("暂停");
                        Toast.makeText(getApplicationContext(), "暂停", Toast.LENGTH_LONG).show();
                        mAudioPlayerHelper.resume();

                    } else {
                        tvPlay.setText("播放");
                        Toast.makeText(getApplicationContext(), "播放", Toast.LENGTH_LONG).show();
                        // mAudioPlayerHelper
                        //         .path(mAudioRecorderHelper.getUniteAudioFile().getAbsolutePath())
                        //         .start();
                        mAudioPlayerHelper
                                .path(mCurrentPlayingUrl)
                                .start();
                        isClickToPlay = !isClickToPlay;
                    }
                }
            }
        });
        mAudioPlayerHelper.setOnPlayerStateChangeListener(new SimpleOnPlayerStateChangeListener() {
            @Override
            public void onProgress(int progress, String dataSource) {
                tvTime.setText(getTimeStrFromMillis(progress));
            }

            @Override
            public void onGetMaxDuration(int maxDuration, String dataSource) {
                tvTotalTime.setText(getTimeStrFromMillis(maxDuration));
            }
        });
        mAudioRecorderHelper.setOnRecordStateChangeListener(new SimpleOnRecordStateChangeListener());
    }

    public static String getTimeStrFromMillis(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss", Locale.getDefault());
        String result = sdf.format(new Date(time));
        return result;
    }

    @Override
    protected void onStop() {
        super.onStop();
        mAudioRecorderHelper.stop();
    }

    public String[] getPermissionArr() {
        return new String[]{
                Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.INTERNET
        };
    }

    private boolean isPermissionGrant(Context context) {
        boolean result = false;
        for (String item : permissions) {
            result &= context.checkPermission(item, android.os.Process.myPid(),
                    Process.myUid()) == PackageManager.PERMISSION_GRANTED;
        }
        return result;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == this.REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this,
                        "请授予全部权限",
                        Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
}
